<template>
	<view class="content">
		<u-navbar title=" " leftIcon=" " placeholder :bgColor="bgColor" :border="false">
			<view class="search-wrap" slot="center">
				<u-search v-model="searchValue" placeholder="搜索知识库" bgColor="#ffffff" :showAction="false"
					inputAlign="center" @search="onSearch" />
			</view>
		</u-navbar>
		<!-- <view class="h1">
			<view class="mr-15">我的知识库</view>
			<u-icon name="plus" color="#000" size="20" bold @click="addKnowledgeClick"></u-icon>
		</view> -->
		<view class="tab-container">
			<u-tabs :list="tabList" :current="currentTab" lineColor="#d9822b" @change="onTabChange"
				itemStyle="padding: 8rpx 24rpx; font-size: 42rpx; font-weight: 600; color: #333333;" />
			<!-- 新增知识库 只在个人知识库tag页显示 -->
			<view class="icon-group" v-if="tabList[currentTab].type === 1">
				<view class="icon-item">
					<u-icon name="plus" size="36rpx" color="#000" bold @click="addKnowledgeClick" />
				</view>
			</view>
		</view>


		<view class="scroll-wrap">
			<scroll-view class="scroll-view_H" scroll-y @scrolltolower="loadMore" :lower-threshold="50">
				<view class="knowledge-container">
					<view class="knowledge-li" v-for="(item, i) in list" :key="i" @click="goKnowledgeDetail(item)"
						@longpress="() => goChooseQuestionsPage(item)">
						<view class="top">
							<view class="top-left">
								<view style="font-weight: bold;">🧠 {{ item.name }}</view>
								<view class="font-24">笔记数量：{{ item.num || 0 }}</view>
							</view>
							<view class="top-right">
								{{ handlePattern(item) }}
							</view>
						</view>
						<view class="bottom shadow" style="background-color: white; font-size: 26rpx; color: #333;">
							{{ item.title || '暂无描述' }}
						</view>
						<!-- 编辑/删除知识库按钮  只在个人知识库tab页显示 -->
						<view class="knowledge-icon-group" v-if="tabList[currentTab].type === 1">
							<view class="icon-item" v-if="tabList[currentTab].type === 1">
								<u-icon name="trash" size="36rpx" color="#F16C40" bold
									@tap.stop.prevent="openDeleteConfirm(item.id)" />
							</view>
							<view class="icon-item" v-if="tabList[currentTab].type === 1">
								<u-icon name="edit-pen" size="36rpx" color="#F16C40" bold
									@tap.stop.prevent="editKnowledge(item)" />
							</view>
						</view>
					</view>
					<view v-if="loading" class="loading-text">
						加载中...
					</view>
					<view v-if="noMore" class="no-more-text">
						没有更多数据了
					</view>
					<view v-if="!noMore && list.length === 0" class="no-data-text">
						暂无个人知识库，点击立即创建吧～
					</view>
				</view>
			</scroll-view>
		</view>
		<custom-tab-bar :currentIndex="0"></custom-tab-bar>
		<tn-modal v-model="showAddModel" :custom="true" :maskCloseable="false" :showCloseBtn="true">
			<tn-form :model="addModelForm" ref="addModelForm" :errorType="['message']" labelWidth="200"
				:borderBottom="false">
				<tn-form-item label="知识库名称:" prop="name" :borderBottom="false" required>
					<tn-input v-model="addModelForm.name" border />
				</tn-form-item>
				<tn-form-item label="知识库描述:" prop="title" :borderBottom="false" required>
					<tn-input v-model="addModelForm.title" border />
				</tn-form-item>
				<tn-form-item label="类型:" prop="type" :borderBottom="false" required>
					<tn-input v-model="addModelForm.typeLabel" border disabled @click="selectShow=true" />
				</tn-form-item>
				<tn-form-item style="display: flex; justify-content: flex-end;" :borderBottom="false">
					<tn-button @click="handleFormSubmit" backgroundColor="#FFF9F3" fontColor="black">保存</tn-button>
					<tn-button @click="handleFormCancel" backgroundColor="#FFF9F3" fontColor="black"
						style="margin-left: 10px;">取消</tn-button>
				</tn-form-item>
			</tn-form>
		</tn-modal>
		<tn-select v-model="selectShow" mode="single" :list="typeOptions" @confirm="confirm" :safeAreaInsetBottom="true"
			:maskCloseable="false" :searchShow="false"></tn-select>


		<!-- 编辑知识库弹窗 -->
		<tn-modal v-model="showEditModel" :custom="true" :maskCloseable="false" :showCloseBtn="true">
			<tn-form :model="editModelForm" ref="editModelForm" :errorType="['message']" labelWidth="200"
				:borderBottom="false">
				<tn-form-item label="知识库名称:" prop="name" :borderBottom="false" required>
					<tn-input v-model="editModelForm.name" border />
				</tn-form-item>
				<tn-form-item label="知识库描述:" prop="title" :borderBottom="false" required>
					<tn-input v-model="editModelForm.title" border />
				</tn-form-item>
				<tn-form-item label="类型:" prop="typeValue" :borderBottom="false" required>
					<tn-input v-model="editModelForm.typeLabel" border disabled @click="selectShowEdit = true" />
				</tn-form-item>
				<tn-form-item style="display: flex; justify-content: flex-end;" :borderBottom="false">
					<tn-button @click="handleEditSubmit" backgroundColor="#FFF9F3" fontColor="black">保存</tn-button>
					<tn-button @click="handleEditCancel" backgroundColor="#FFF9F3" fontColor="black"
						style="margin-left: 10px;">取消</tn-button>
				</tn-form-item>
			</tn-form>
		</tn-modal>
		<tn-select v-model="selectShowEdit" mode="single" :list="typeOptions" @confirm="confirmEdit"
			:safeAreaInsetBottom="true" :maskCloseable="false" :searchShow="false"></tn-select>

		<!-- 删除确认弹窗 -->
		<tn-modal v-model="showDeleteModal" title="确认删除知识库" :custom="true">
			<view>是否确认删除该知识库？删除后将无法恢复！</view>
			<view style="display: flex; justify-content: flex-end; margin-top: 20rpx;">
				<tn-button @click="showDeleteModal = false">取消</tn-button>
				<tn-button @click="confirmDeleteKnowledge" style="margin-left: 20rpx;">删除</tn-button>
			</view>
		</tn-modal>



		<tn-toast ref="toast"></tn-toast>
	</view>
</template>

<script>
	import knowledgeInfo from '@/api/index.js';
	import loginInfo from '@/api/login.js';
	export default {
		data() {
			return {

				// 编辑知识库弹窗
				showEditModel: false,
				editModelForm: {
					id: '',
					name: '',
					title: '',
					typeLabel: '',
					typeValue: ''
				},


				// 删除知识库
				showDeleteModal: false,
				deleteId: null,



				searchValue: '', // 知识库搜索结果
				tabList: [{
						name: 'Tigo知识库',
						type: 0
					},
					{
						name: '个人知识库',
						type: 1
					},
				],
				currentTab: 0, // 默认展示个人知识库


				bgColor: "transparent",
				list: [], // 数据列表
				showAddModel: false, // 新增知识库弹框标识
				addModelForm: {
					name: '',
					title: '',
					typeLabel: '',
					typeValue: ''
				},
				value: '',
				type: 'select',
				show: false,
				border: true,
				page: 1, // 当前页码
				pageSize: 10, // 每页条数
				loading: false, // 是否正在加载
				noMore: false, // 是否没有更多数据
				rules: {
					name: [{
						required: true,
						message: '请输入知识库名称',
						trigger: ['change', 'blur'],
					}],
					title: [{
						required: true,
						message: '请输入知识库描述',
						trigger: ['change', 'blur'],
					}],
					typeValue: [{
						required: true,
						message: '请输入类型',
						trigger: ['change', 'blur'],
					}]
				},
				selectShow: false,
				typeOptions: [{
						id: '0',
						label: '公开',
						value: '0',
					},
					{
						id: '1',
						label: '付费',
						value: '1'
					},
					{
						id: '2',
						label: '私密',
						value: '2'
					}
				],
			}
		},
		onLoad() {

		},
		onShow() {
			this.getList(); // 初始化加载数据
		},
		onReady() {
			this.$refs.addModelForm.setRules(this.rules);
			this.$refs.editModelForm.setRules(this.rules);
		},
		mounted() {
			this.getList(); // 初始化加载数据
		},
		methods: {

			// 删除知识库弹窗
			openDeleteConfirm(id) {
				this.deleteId = id;
				this.showDeleteModal = true;
			},
			// 删除知识库
			async confirmDeleteKnowledge() {
				try {
					await knowledgeInfo.deleteKnowledgeBase(this.deleteId);
					this.$u.toast('删除成功');
					// 刷新列表
					await this.getList();
				} catch (e) {
					this.$u.toast('删除失败，请重试！');
				} finally {
					this.showDeleteModal = false;
				}
			},


			// 打开编辑弹窗
			editKnowledge(item) {
				this.editModelForm = {
					id: item.id,
					name: item.name,
					title: item.title,
					typeLabel: this.handlePattern(item),
					typeValue: String(item.pattern)
				};
				this.showEditModel = true;
			},

			// 编辑弹窗关闭
			handleEditCancel() {
				this.showEditModel = false;
			},

			// 编辑选择类型确认
			confirmEdit(e) {
				this.editModelForm.typeLabel = e[0].label;
				this.editModelForm.typeValue = e[0].value;
			},

			// 更新知识库
			async handleEditSubmit() {
				this.$refs.editModelForm.validate(async (valid) => {
					if (valid) {
						try {
							const editData = {
								id: this.editModelForm.id,
								name: this.editModelForm.name,
								title: this.editModelForm.title,
								pattern: this.editModelForm.typeValue
							};
							const res = await knowledgeInfo.updataKnowledgeBase(editData);
							if (res.data.code == 200) {
								this.$refs.toast.show({
									content: '修改成功',
									icon: 'success',
									duration: 1000
								});
								this.page = 1;
								this.list = [];
								this.noMore = false;
								await this.getList();
							}
						} catch (err) {
							console.error('修改失败:', err);
						} finally {
							this.showEditModel = false;
						}
					}
				});
			},


			// 进入刷题选择笔记页
			goChooseQuestionsPage(item) {
				const knowledgeType = this.tabList[this.currentTab].type;
				uni.navigateTo({
					url: `chooseQuestions?knowledgeBaseId=${item.id}&knowledgeType=${knowledgeType}&knowledgeBaseName=${item.name}`
				});
			},

			// 顶部tab切换
			onTabChange(event) {
				this.currentTab = event.index;
				this.page = 1;
				this.list = [];
				this.noMore = false;
				this.getList();
			},


			// 获取数据
			async getList() {
				try {
					const knowledgeType = this.tabList[this.currentTab].type;

					const queryData = {
						pageQueryDTO: {
							currentPage: this.page,
							pageSize: this.pageSize
						},
						type: uni.getStorageSync('bindType'),
						// code: uni.getStorageSync('bindCode'),
					}
					// 👇 根据 tab 类型动态添加字段
					if (knowledgeType === 0) {
						queryData.displaySystemKnowledge = 1;
					} else if (knowledgeType === 1) {
						queryData.userId = uni.getStorageSync('userId');
					}

					const res = await knowledgeInfo.getKnowledgeListApi(queryData);
					if (res.data.code == 200) {
						if (this.page === 1) {
							this.list = res.data.data?.content;
						} else {
							this.list = [...this.list, ...res.data.data?.content];
						}
						if (res.data.length < this.pageSize) {
							this.noMore = true;
						} else {
							this.page++;
						}
					}
				} catch (error) {
					if (error.data.code == 401) {
						uni.clearStorageSync();
						// 1. 获取微信jsCode
						const loginRes = await uni.login({
							provider: 'weixin',
							onlyAuthorize: true
						});
						const jsCode = loginRes.code;
						// 2. 发送jsCode到后端
						const res = await loginInfo.loginApi(jsCode);
						// 3. 处理响应
						if (res.data.code === 200) {
							// 登录成功，保存token和用户信息
							uni.setStorageSync('token', res.data.data?.token);
							uni.setStorageSync('userId', res.data.data?.userId);
							uni.setStorageSync('bindCode', res.data.data?.bindCode);
							uni.setStorageSync('bindType', res.data.data?.bindType);
							this.getList();
						} else {
							// 处理其他情况
							throw new Error(res.data.data.message || '登录失败');
						}
					} else {
						console.error("加载失败:", error);
					}
				} finally {}
			},
			// 上拉加载更多
			loadMore() {
				this.getList();
			},
			handlePattern(value) {
				if (value.knowledgeType == 1) {
					switch (value.pattern) {
						case 0:
							return '公开';
						case 1:
							return '付费';
						default:
							return '私密';
					}
				} else {
					return '公开'
				}
			},
			confirm(e) {
				this.addModelForm.typeLabel = e[0].label
				this.addModelForm.typeValue = e[0].value
			},
			onSelect(e) {
				const {
					name,
					value
				} = e
				this.formData[name] = value
			},
			// 表单取消
			handleFormCancel() {
				this.showAddModel = false;
			},
			// 表单提交
			async handleFormSubmit() {
				this.$refs.addModelForm.validate(async (valid) => {
					if (valid) {
						try {
							const addFormData = {
								name: this.addModelForm.name,
								title: this.addModelForm.title,
								pattern: this.addModelForm.typeValue,
								userId: uni.getStorageSync('userId'),
								type: uni.getStorageSync('bindType'),
								knowledgeType: this.addModelForm.knowledgeType,
								code: uni.getStorageSync('bindCode'),
							};
							const res = await knowledgeInfo.addKnowledgeListApi(addFormData);
							if (res.data.code == 200) {
								this.$refs.toast.show({
									title: '',
									content: '新增成功',
									icon: 'success',
									image: '',
									duration: 1000
								});

								this.page = 1;
								this.pageSize = 10;
								this.list = [];
								this.noMore = false;
								await this.getList();
							}
						} catch (error) {
							console.error("加载失败:", error);
						} finally {
							this.showAddModel = false;
						}
					}
				});
			},
			addKnowledgeClick() {
				this.showAddModel = true;
			},

			// 知识库搜索框跳转
			onSearch(val) {
				// 如果为空可以给出提示
				// if (!val || val.trim() === '') {
				// 	uni.showToast({
				// 		title: '请输入搜索内容',
				// 		icon: 'none'
				// 	});
				// 	return;
				// }

				// 跳转并传参
				uni.navigateTo({
					url: `./searchList?combineSearch=1&name=${val}`
				});
			},

			goKnowledgeDetail(data) {
				const paramObj = {
					id: data.id,
					name: data.name,
					type: data.knowledgeType
				}
				uni.navigateTo({
					url: './knowledgeDetail?params=' + encodeURIComponent(JSON.stringify(paramObj))
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.icon-group {
		display: flex;
		align-items: center;
		margin-left: 20rpx;
		/* 与 tabs 的间距 */
	}

	.knowledge-icon-group {
		display: flex;
		align-items: center;
		/* 垂直居中 */
		justify-content: flex-end;
		/* 靠右对齐 */
		padding: 0 20rpx;
		/* 调整为你需要的高度 */
		height: 80rpx;
	}

	.icon-item {
		margin-left: 30rpx;
		background-color: #f5f5f5;
		/* 图标之间的间距 */
	}


	.search-wrap {
		width: 200px;
		height: 33px;
		border-radius: 20px;
		opacity: 1;
		background: #FCFCFC;
	}

	.h1 {
		display: flex;
		align-items: center;
		font-size: 42rpx;
		font-weight: 600;
		color: #000;
		margin: 40rpx 0 40rpx 24rpx;
	}

	.scroll-wrap {
		width: 100%;
		height: calc(100vh - 220px);

		.scroll-view_H {
			height: 100%;

			.knowledge-container {
				display: flex;
				flex-wrap: wrap;
				padding: 16px;
				box-sizing: border-box;

				.knowledge-li {
					width: calc(50% - 10px);
					margin: 5px;
					background: #fff;
					border-radius: 8px;
					overflow: hidden;
					box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
				}

				.top {
					padding: 20rpx;
					display: flex;
					justify-content: space-between;
					border-bottom: 1px solid #f5f5f5;
					background: #FFF9F3;

					.top-left {
						display: flex;
						flex-direction: column;
						justify-content: space-between;
						flex: 1
					}

					.top-right {
						width: 46rpx;
						height: 46rpx;
						border-radius: 50%;
						border: 1px solid #000;
						font-size: 18rpx;
						display: flex;
						justify-content: center;
						align-items: center;
					}
				}

				.bottom {
					height: 70px;
					display: flex;
					align-items: center;
					padding: 10px;
				}

				.font-24 {
					font-size: 24rpx;
					color: #999;
					margin-top: 8px;
				}

				.shadow {
					box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
				}

				.loading-text,
				.no-more-text {
					width: 100%;
					text-align: center;
					display: flex;
					justify-content: center;
					padding: 20rpx;
					color: #999;
				}
			}
		}
	}

	.tab-container {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 20rpx;
		margin-top: 20rpx;
	}

	// 知识库无数据显示ui
	.no-data-text {
		width: 100%;
		text-align: center;
		color: #999;
		padding: 40rpx 0;
		font-size: 28rpx;
	}
</style>